<script setup>
import DictSelect from '@/components/dict-select/index.vue'
import ConfirmButton from "@/components/confirm-button/index.vue";
import {dictCode} from "@/common/constant.js";
import {h} from "vue";
import {AddOutline, Trash} from '@vicons/ionicons5'
import {renderIcon} from "@/utils/index.js";
import {NButton, NSpace, useDialog, useMessage} from "naive-ui";
import {useSysUserMutations} from "@/composables/sys/user.js";
import {usePermission} from "@/composables/use-permission.js";

const emits = defineEmits([
  'on-add', 'on-edit', 'update:page', 'update:pageSize'
])

const checkedRowKeys = ref([])
const sysUserMutations = useSysUserMutations()
const dialog = useDialog()
const message = useMessage()
const {hasPermission} = usePermission()

defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  page: {
    type: Number,
    required: true
  },
  pageSize: {
    type: Number,
    required: true
  },
  itemCount: {
    type: Number,
    required: true
  }
})
// 列配置
const columns = [
  {
    type: 'selection',
    width: 60
  },
  {
    title: '用户名',
    key: 'username',
    align: 'center',
  },
  {
    title: '昵称',
    key: 'nickname',
    align: 'center',
  },
  {
    title: '头像',
    key: 'avatar',
    align: 'center',
  },
  {
    title: '状态',
    key: 'status',
    align: 'center',
    width: '100',
    render: (row) => {
      return h(DictSelect, {
        code: dictCode.SYS_USER_STATUS,
        value: row.status,
        disabled: true
      })
    }
  },
  {
    title: '创建时间',
    key: 'createdAt',
    align: 'center',
  },
  {
    title: '创建人',
    key: 'createdByName',
    align: 'center'
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    align: 'center',
  },
  {
    title: '更新人',
    key: 'updatedByName',
    align: 'center'
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    width: 200,
    render(row) {
      const isAdmin = row.id === '1'
      return [
        hasPermission('delete') && !isAdmin ?
            h(ConfirmButton,
                {
                  text: '删除',
                  type: 'error',
                  size: 'tiny',
                  quaternary: true,
                  onPositiveClick: () => {
                    emits('on-delete', row.id)
                  }
                }
            ) : null,
        hasPermission('resetPassword') && !isAdmin ?
            h(ConfirmButton,
                {
                  text: '重置密码',
                  type: 'warning',
                  size: 'tiny',
                  quaternary: true,
                  onPositiveClick: () => {
                    handleResetPassword(row.id)
                  }
                }
            ) : null,
        hasPermission('lock') && !isAdmin ?
            h(ConfirmButton,
                {
                  text: `${row.status === 'NORMAL' ? '锁定' : '解锁'}`,
                  type: 'warning',
                  size: 'tiny',
                  quaternary: true,
                  onPositiveClick: () => {
                    if (row.status === 'NORMAL') {
                      handleLock(row.id)
                    } else {
                      handleUnlock(row.id)
                    }
                  }
                }
            ) : null,
        hasPermission('update') && !isAdmin ?
            h(NButton, {
              type: 'primary',
              size: 'tiny',
              quaternary: true,
              onClick: () => {
                emits('on-edit', row.id)
              }
            }, {
              default: () => '编辑'
            }) : null,
      ]
    }
  }
]
// 重置密码
const handleResetPassword = async (id) => {
  const {code, data} = await sysUserMutations.resetPassword.mutateAsync(id)
  if (code === 1) {
    dialog.warning({
      title: '密码重置成功',
      content: `新密码为：${data}，请妥善保管！`,
      positiveText: '我知道了',
      closable: false,
      maskClosable: false
    })
  }
}

// 锁定
const handleLock = async (id) => {
  const {code} = await sysUserMutations.lock.mutateAsync(id)
  if (code === 1) {
    message.success('用户已锁定')
  }
}
// 解锁
const handleUnlock = async (id) => {
  const {code} = await sysUserMutations.unlock.mutateAsync(id)
  if (code === 1) {
    message.success('用户已解锁')
  }
}

</script>

<template>
  <n-space vertical>
    <n-space reverse>
      <n-button
          v-permission="'create'"
          type="primary"
          size="small"
          :render-icon="renderIcon(AddOutline)"
          @click="$emit('on-add')">
        <span>新增</span>
      </n-button>
      <confirm-button
          v-permission="'delete'"
          text="批量删除"
          type="error" size="small"
          :disabled="checkedRowKeys.length === 0"
          :render-icon="renderIcon(Trash)"
          @positive-click="$emit('on-delete-batch', checkedRowKeys)"
      />
    </n-space>
    <n-data-table
        ref="table"
        remote
        v-model:checked-row-keys="checkedRowKeys"
        :row-key="(row) => row.id"
        :columns="columns"
        :data="data"
        :pagination="{
        page,
        pageSize,
        itemCount: itemCount,
        showSizePicker: true,
        showQuickJumper: true,
        goto: () => '跳至',
        pageSizes: [10, 20, 50, 100],
        showTotal: true,
        prefix: () => `共${itemCount}条`,
        'onUpdate:page': (_page) => $emit('update:page', _page),
        'onUpdate:pageSize': (_pageSize) => $emit('update:pageSize', _pageSize),
      }">
    </n-data-table>
  </n-space>
</template>

<style scoped>

</style>